package com.boboPlanet.user.filter;

import com.boboPlanet.comm.context.TraceIdContext;
import com.boboPlanet.comm.enums.PlanetCommCode;
import com.boboPlanet.comm.thread.ThreadMdcUtil;
import com.boboPlanet.comm.thread.TraceIdAutoGenerate;
import io.reactivex.rxjava3.annotations.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2023/5/7
 * @Company planet
 **/
@Component
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String tid = TraceIdAutoGenerate.traceByUuid();
        String traceId = request.getHeader(PlanetCommCode.COMM_LOG_KEY.getCode());
        //可以考虑让客户端传入链路ID，但需保证一定的复杂度唯一性；如果没使用默认UUID自动生成
        if (!StringUtils.isEmpty(traceId)){
            tid=traceId;
        }
        request.setAttribute(PlanetCommCode.COMM_LOG_KEY.getCode(),tid);

        TraceIdContext.setTraceId(tid);

        MDC.put(PlanetCommCode.COMM_LOG_KEY.getCode(), tid);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler,
                                @Nullable Exception ex) {
        MDC.remove(PlanetCommCode.COMM_LOG_KEY.getCode());
        ThreadMdcUtil.remove();
        TraceIdContext.remove();
    }
}
